// src/models/category.ts
import mongoose, { Document, Schema } from 'mongoose'
import { Counter } from './counter'
import dayjs from 'dayjs'

export interface ICategory extends Document {
  id: number
  name: string
  code: string
  description: string
  parent_id: number | null
  level: number
  sort_order: number
  image: string
  icon: string
  status: string // 'active' | 'inactive'
  is_visible: boolean
  created_at: string
  updated_at: string
  created_by: number | null
  updated_by: number | null
}

const CategorySchema: Schema = new Schema({
  id: {
    type: Number,
    unique: true,
    description: '分类id'
  },
  name: {
    type: String,
    unique: true,
    required: true,
    description: '分类名称'
  },
  code: {
    type: String,
    unique: true,
    required: true,
    description: '分类编码，用于系统标识'
  },
  description: {
    type: String,
    required: false,
    default: '',
    description: '分类描述'
  },
  parent_id: {
    type: Number,
    default: null,
    description: '父分类id，顶级分类为null'
  },
  level: {
    type: Number,
    required: true,
    default: 1,
    description: '分类层级，从1开始'
  },
  sort_order: {
    type: Number,
    default: 0,
    description: '排序号，值越小越靠前'
  },
  image: {
    type: String,
    required: false,
    default: '',
    description: '分类图片URL'
  },
  icon: {
    type: String,
    required: false,
    default: '',
    description: '分类图标'
  },
  status: {
    type: String,
    enum: ['active', 'inactive'], // active:启用 inactive:禁用
    default: 'active',
    description: '分类状态'
  },
  is_visible: {
    type: Boolean,
    default: true,
    description: '是否可见'
  },
  created_at: {
    type: String,
    default: () => dayjs().format('YYYY-MM-DD HH:mm:ss'),
    description: '创建时间'
  },
  updated_at: {
    type: String,
    default: () => dayjs().format('YYYY-MM-DD HH:mm:ss'),
    description: '最后更新时间'
  },
  created_by: {
    type: Number,
    default: null,
    description: '创建者id'
  },
  updated_by: {
    type: Number,
    default: null,
    description: '最后更新者id'
  }
})

// 保存前处理
CategorySchema.pre<ICategory>('save', async function (next) {
  if (this.isNew) {
    try {
      const counter = await Counter.findByIdAndUpdate(
        { _id: 'category_id' },
        { $inc: { seq: 1 } },
        { new: true, upsert: true }
      )
      this.id = counter.seq
      next()
    } catch (error: any) {
      next(error)
    }
  } else {
    next()
  }
})

// 更新时更新时间戳
CategorySchema.pre<ICategory>('findOneAndUpdate', function (next) {
  this.set({ updated_at: dayjs().format('YYYY-MM-DD HH:mm:ss') })
  next()
})

// 更新时更新时间戳
CategorySchema.pre<ICategory>('findOneAndUpdate', function (next) {
  this.set({ updated_at: dayjs().format('YYYY-MM-DD HH:mm:ss') })
  next()
})

// 添加这段代码来配置 toJSON
CategorySchema.set('toJSON', {
  transform: function (doc, ret) {
    const { _id, __v, ...rest } = ret
    return rest
  }
})

export const Category = mongoose.model<ICategory>(
  'category',
  CategorySchema,
  'category'
)
